package org.example.new_hbps_backend_reconstruction.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.example.new_hbps_backend_reconstruction.service.CalibrationService;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 丁利军
 * @date 2025年10月31日 14:42
 * @description TODO: 描述
 */

@Service
@Slf4j
public class CalibrationServiceImpl implements CalibrationService {

    // 存储WebSocket会话
    private final ConcurrentHashMap<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    @Override
    public void startCalibration(String sessionId) {
        log.info("开始标定，会话ID: {}", sessionId);
        // 这里可以添加标定开始的业务逻辑
    }

    @Override
    public void stopCalibration(String sessionId) {
        log.info("结束标定，会话ID: {}", sessionId);
        WebSocketSession session = sessions.get(sessionId);
        if (session != null && session.isOpen()) {
            try {
                session.close();
                sessions.remove(sessionId);
                log.info("WebSocket连接已关闭，会话ID: {}", sessionId);
            } catch (IOException e) {
                log.error("关闭WebSocket连接失败: {}", e.getMessage());
            }
        }
    }

    @Override
    public void handleWABCMessage(String sessionId, String message) {
        log.info("处理WABC消息，会话ID: {}, 消息: {}", sessionId, message);

        try {
            // 解析客户端发送的WABC消息
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(message);

            String msgType = jsonNode.get("msgType").asText();
            if (!"WABC".equals(msgType)) {
                log.error("无效的消息类型: {}", msgType);
                return;
            }

            // 构造返回值（WBBC消息）
            Map<String, Object> response = new HashMap<>();
            response.put("code", 0);
            response.put("msgType", "WBBC");
            response.put("msg", "ok");
            response.put("minGoodDataCount", 5); // 示例值，根据实际需求调整

            // 发送响应给客户端
            sendMessageToClient(sessionId, response);

        } catch (Exception e) {
            log.error("处理WABC消息失败: {}", e.getMessage());

            // 发送错误响应
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", -1);
            errorResponse.put("msgType", "WBBC");
            errorResponse.put("msg", "消息处理失败: " + e.getMessage());

            sendMessageToClient(sessionId, errorResponse);
        }
    }

    @Override
    public void sendMessageToClient(String sessionId, Object message) {
        WebSocketSession session = sessions.get(sessionId);
        if (session != null && session.isOpen()) {
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                String messageJson = objectMapper.writeValueAsString(message);
                session.sendMessage(new TextMessage(messageJson));
                log.debug("消息发送成功，会话ID: {}, 消息: {}", sessionId, messageJson);
            } catch (IOException e) {
                log.error("发送消息失败: {}", e.getMessage());
            }
        } else {
            log.warn("WebSocket会话不存在或已关闭，会话ID: {}", sessionId);
        }
    }

    @Override
    public boolean validateToken(String token) {
        // TODO: 实现token验证逻辑，参考4.3章节
        // 这里应该是具体的token验证逻辑
        log.info("验证token: {}", token);
        return token != null && !token.trim().isEmpty();
    }

    /**
     * 添加WebSocket会话
     */
    public void addSession(String sessionId, WebSocketSession session) {
        sessions.put(sessionId, session);
        log.info("WebSocket会话已添加，会话ID: {}", sessionId);
    }

    /**
     * 移除WebSocket会话
     */
    public void removeSession(String sessionId) {
        sessions.remove(sessionId);
        log.info("WebSocket会话已移除，会话ID: {}", sessionId);
    }

    /**
     * 获取所有活跃的会话
     */
    public Set<String> getActiveSessions() {
        return sessions.keySet();
    }
}
